package com.sunfeng.n5;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 停止标记用 volatile 是为了保证该变量在多个线程之间的可见性
 *
 * @author sunfeng
 * @date 2021/04/13 16:18
 **/

@Slf4j(topic = "c.TPTVolatile")
public class TPTVolatile {

    private Thread thread;

    private volatile boolean stop = false;


    public static void main(String[] args) throws InterruptedException {
        TPTVolatile aVolatile = new TPTVolatile();
        aVolatile.start();
        Thread.sleep(3500);
        log.debug("stop");
        aVolatile.stop();

    }


    public void start() {
        thread = new Thread(() -> {

            while (true) {
                if (stop) {
                    log.debug("料理后事");
                    break;
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                    log.debug("将结果保存");
                } catch (InterruptedException e) {
                    log.error("线程被打断");
                }
            }

        }, "监控线程");

        thread.start();
    }

    public void stop() {
        stop = true;
        thread.interrupt();
    }
}
